package com.hospital.controller;

import com.alibaba.fastjson.JSONObject;
import com.hospital.entity.Patient;
import com.hospital.mapper.PatientMapper;
import com.hospital.tools.JsonResult;
import com.hospital.tools.MD5Utils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

@RestController
@RequestMapping("/patient")
public class PatientController {

    @Resource
    PatientMapper patientMapper;

    // 注册
    @PostMapping("/register")
    public JsonResult patientRegister(
            @Valid @RequestBody Patient patient,
            BindingResult bindingResult
    ) {
        for (ObjectError error : bindingResult.getAllErrors()) {
            // 100 为参数错误
            return JsonResult.json_error("100", error.getDefaultMessage());
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String birth = patient.getPatient_idcard().substring(6, 14); // 获取生日部分
            patient.setPatient_birth(sdf.parse(birth));

            patient.setPatient_gender((patient.getPatient_idcard().charAt(16) - '0') % 2);

            patient.setPatient_priority(0);
            patient.setPatient_block(0);

            int res = patientMapper.insertPatient(patient);
            return res == 1 ?
                    JsonResult.json_ok("注册成功") :
                    JsonResult.json_error("400", "注册失败，原因未知");
        } catch (DuplicateKeyException e) {
            return JsonResult.json_error("401", "身份证或手机号码已经存在");
        } catch (ParseException e) {
            return JsonResult.json_error("402", "身份证格式错误: 生日部分");
        }
    }

    @PostMapping("/login")
    public JsonResult login(
            @Valid @NotNull(message = "参数不可为空") @RequestBody String params,
            BindingResult bindingResult
    ) {
        // 100 为参数错误
        for (ObjectError error : bindingResult.getAllErrors())
            return JsonResult.json_error("100", error.getDefaultMessage());

        JSONObject jsonObject = JSONObject.parseObject(params);

        String Phone = jsonObject.getString("phone");
        if (Phone == null || "".equals(Phone)) {
            return JsonResult.json_error("301", "手机号不得为空");
        }

        String Password = jsonObject.getString("password");
        if (Password == null || "".equals(Password)) {
            return JsonResult.json_error("302", "密码不得为空");
        }

        Patient patient = patientMapper.getPatientByPhone(Phone);
        if (patient == null) {
            return JsonResult.json_error("303", "账户不存在");
        }
        if (patient.getPatient_block() == 1) {
            return JsonResult.json_error("305", "账户在黑名单");
        }

        String TruePassword = patient.getPatient_password();

        if (TruePassword.equals(MD5Utils.getMD5(Password))) {
            return JsonResult.json_ok(patient);
        }
        return JsonResult.json_error("304", "密码错误");
    }

    @PostMapping("/update")
    public JsonResult updatePatient(
            @Valid @NotNull(message = "参数不可为空") @RequestBody Patient patient,
            BindingResult bindingResult
    ) {
        // 100 为参数错误
        for (ObjectError error : bindingResult.getAllErrors())
            return JsonResult.json_error("100", error.getDefaultMessage());

        try {
            int res = patientMapper.updatePatient(patient);
            return res == 1 ?
                    JsonResult.json_ok("修改成功") :
                    JsonResult.json_error("401", "修改失败，原因未知");
        } catch (Exception e) {
            return JsonResult.json_error("400", "病人账户不存在");
        }
    }

    // 后台更改病人，权限更高
    @PostMapping("/ex_update")
    public JsonResult updatePriority(
            @Valid  @RequestBody Patient patient,
            BindingResult bindingResult
    ) {
        for (ObjectError error : bindingResult.getAllErrors()) {
            // 100 为参数错误
            return JsonResult.json_error("100", error.getDefaultMessage());
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String birth = patient.getPatient_idcard().substring(6, 14); // 获取生日部分
            patient.setPatient_birth(sdf.parse(birth));

            patient.setPatient_gender((patient.getPatient_idcard().charAt(16) - '0') % 2);

            int res = patientMapper.EX_updatePatient(patient);
            return res == 1 ?
                    JsonResult.json_ok("修改成功") :
                    JsonResult.json_error("402", "修改失败，原因未知");
        } catch (ParseException e) {
            return JsonResult.json_error("401", "身份证格式错误: 生日部分");
        } catch (Exception e) {
            return JsonResult.json_error("400", "病人账户不存在");
        }
    }
}
